package com.example.demo.service.impl;

import com.example.demo.dto.CartItemDetailsDTO;
import com.example.demo.entity.ShoppingCart;
import com.example.demo.mapper.ShoppingCartMapper;
import com.example.demo.service.ShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
 * <p>
 * 购物车管理 服务实现类
 * </p>
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<ShoppingCart> getUserCart(Integer userId) {
        return shoppingCartMapper.selectByUserId(userId);
    }


    @Override
    @Transactional
    public String updateCartItem(ShoppingCart cartItem) {
        ShoppingCart existingItem = shoppingCartMapper.selectById(cartItem.getSId());
        if (existingItem == null) {
            return "购物车商品不存在";
        }

        existingItem.setSQuantity(cartItem.getSQuantity());
        shoppingCartMapper.updateById(existingItem);
        return "购物车商品数量已更新";
    }

    @Override
    @Transactional
    public String removeFromCart(Integer cartId) {
        ShoppingCart item = shoppingCartMapper.selectById(cartId);
        if (item == null) {
            return "购物车商品不存在";
        }

        shoppingCartMapper.deleteById(cartId);
        return "商品已从购物车移除";
    }

    @Override
    @Transactional
    public String clearCart(Integer userId) {
        int deleted = shoppingCartMapper.deleteByUserId(userId);
        return "已清空购物车，共移除 " + deleted + " 件商品";
    }

    public BigDecimal getCartTotalAmount(Integer userId) {
        BigDecimal amount = shoppingCartMapper.getCartTotalAmount(userId);
        return amount != null ? amount : BigDecimal.ZERO;
    }

    public Integer getTotalCartItems(Integer userId) {
        Integer count = shoppingCartMapper.getTotalCartItems(userId);
        return count != null ? count : 0;
    }

    @Transactional
    public String batchRemoveItems(Integer userId, List<Integer> cartItemIds) {
        int deleted = shoppingCartMapper.batchDeleteCartItems(cartItemIds);
        return "已成功移除 " + deleted + " 件商品";
    }

    @Override
    public int countCartAddsByGoodsId(Integer goodsId) {
        return shoppingCartMapper.countByGoodsId(goodsId);
    }

    @Override
    public List<CartItemDetailsDTO> getCartDetails(Integer userId) {
        return shoppingCartMapper.selectCartDetailsByUserId(userId);
    }
}
